import request, { requestOld } from '@/utils/request'
import { batchTask } from '../deviceMonitor/work'
import { Message } from 'element-ui'

// 召测用电参数
export function ueCall(query) {
  return batchTask({
    newUrl: '/param/ue/call',
    oldUrl: '/ChaobiaoModule/Tparam_ue/GetCheckData',
    meterNos: query.meterNos,
    rooms: query.rooms,
    updateUrl: '/old/refresh/param/ue',
    onItemOver: query.onItemOver
  })
}

// 列表
export function ueList(query) {
  return request({
    url: '/param/ue/list',
    method: 'get',
    params: query
  })
}

// 设置用电参数
export async function ueSet(data, onItemOver) {
  const oldItems = []
  const newItems = []
  data.forEach((item, i) => {
    // 设备编号/电表号大于255的是老系统电表，调老接口
    if (Number(item.meterNo) > 255) {
      oldItems.push(data[i])
    } else {
      newItems.push(data[i])
    }
  })
  const tasks = []
  for (const item of newItems) {
    // 新系统接口
    tasks.push(() => request({
      url: '/param/ue/set',
      method: 'post',
      data: [item]
    }).then(res => {
      return {
        ...item,
        roomId: item.roomId,
        status: res.data.statusList?.[0]?.status + '' || '1'
      }
    }))
  }
  if (oldItems.length > 0) {
    // 旧系统接口，旧系统接口只支持一个一个改，要调用多次接口
    tasks.push(...oldItems.map(oldRoom => {
      const data = new FormData()
      data.append("Room", oldRoom.roomId)
      // 这个回路固定都是1不用改
      data.append("LoopNo", 1)
      data.append("maxZgl", oldRoom.maxZgl)
      data.append("maxZxgl", oldRoom.maxZxgl)
      data.append("maxSdgl", oldRoom.maxSdgl)
      data.append("maxGxgl", oldRoom.maxGxgl)
      data.append("maxZgl", oldRoom.maxZgl)
      data.append("maxLockCn", oldRoom.maxLockCn)
      data.append("delayTm1", oldRoom.delayTm1)
      data.append("delayTm2", oldRoom.delayTm2)
      data.append("delayTm3", oldRoom.delayTm3)
      return () => requestOld({
        url: '/ChaobiaoModule/Tparam_ue/SubmitParam?RoomId=' + oldRoom.roomId,
        method: 'post',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        data
      }).then(res => {
        return {
          ...oldRoom,
          status: res.status,
          roomId: oldRoom.roomId
        }
      }, err => {
        return {
          ...oldRoom,
          status: '1',
          roomId: oldRoom.roomId
        }
      })
    }))
  }
  async function nextTask() {
    const task = tasks.shift()
    if (!task) {
      return
    }
    const res = await task()
    onItemOver?.(res)
    await nextTask()
  }
  await nextTask()
  // 合并新系统和老系统的接口返回，保持和原来数据格式一样
  if (oldItems.length > 0) {
    await request({
      url: '/old/refresh/param/ue',
      method: 'get',
      params: {
        roomIds: oldItems.map(item => item.roomId).toString()
      }
    }).catch(err => {
      Message.error('同步失败')
    })
  }
}

// 删除用电参数
export function ueDel(query) {
  return request({
    url: '/param/ue/del',
    method: 'get',
    params: query
  })
}
